import axios from 'axios'
import qs from 'qs'

import config from '@/config'
import apis from './api'

import { message } from 'antd'

//创建axios实例
var instance = axios.create({
    baseURL: config.baseURL,
    timeout: 10000,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
    transformRequest: [function (data) {
        //在向服务器发送前，修改请求数据
        return data instanceof FormData ? data : qs.stringify(data)
    }],
    withCredentials: true
})

// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    const responseData = response.data
    if (responseData.code !== 200) {
        message.error(responseData.data)
        //返回自定义信息
        return Promise.reject({
            code: 500,
            info: responseData.data
        });
    } else {
        return {
            code: response.status,
            data: responseData.data
        }
    }
}, function (error) {
    //提示
    message.error('服务器无响应')
    //响应
    return Promise.reject({
        code: 500,
        error
    });
});

const fetch = function (axiosInstance, apiMap) {
    let http = {}
    //填充http
    Object.keys(apiMap).forEach(requestMethod => {
        const method = apiMap[requestMethod]
        Object.keys(method).forEach(api => {
            http[api] = data => {
                return axiosInstance({
                    url: method[api],
                    method: requestMethod,
                    [requestMethod.toUpperCase() === 'POST' ? 'data' : 'params']: data
                })
            }
        })
    })
    return http
}

export default fetch(instance, apis)